package com.open.server.api.tool;

import com.open.common.model.Page;
import com.open.common.model.PageRequest;
import com.open.common.model.Result;
import com.open.common.utils.ExcelUtils;
import com.open.tool.dispatch.IGenerateDispatch;
import com.open.generate.model.TableData;
import com.open.base.model.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.util.List;

/**
 * 代码生成器
 *
 * @author 大树03
 * @date 2025-03-27 22:57
 */
@Slf4j
@RestController
@RequestMapping("/tool/generate")
public class GenerateApi {

    @Autowired
    private IGenerateDispatch generateDispatch;

    /**
     * 分页查询
     *
     * @param pageRequest 分页查询条件
     * @return
     */
    @PostMapping("findPage")
    public Result<Page<TableData>> findPage(@RequestBody PageRequest<TableData> pageRequest) {
        long now = System.currentTimeMillis();
        Result<Page<TableData>> result = new Result<>();
        result.setData(generateDispatch.findPage(pageRequest.getPage(), pageRequest.getModel()));
        result.setTime(System.currentTimeMillis() - now);
        return result;
    }

    /**
     * 代码生成
     */
    @PostMapping("codeGenerate")
    public void codeGenerate(HttpServletResponse response, @RequestBody List<String> tableNames) {
        byte[] bytes = generateDispatch.codeGenerate(tableNames);
        //saveAsFile(bytes, "code.zip");
        ExcelUtils.genCode(response, bytes, "code.zip");
    }

    /**
     * 将字节数组保存为 ZIP 文件
     *
     * @param data      ZIP 文件的字节数组
     * @param filePath  文件保存路径（包括文件名）
     */
    public static void saveAsFile(byte[] data, String filePath) {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(data);
        }catch (Exception e){
            log.error("生成zip文件失败", e);
        }
    }

    /**
     * 测试数据库连接
     */
    @PostMapping("test/connection")
    public Result<Boolean> testConnection(@RequestBody DataSource dataSource) {
        long now = System.currentTimeMillis();
        Result<Boolean> result = new Result<>();
        result.setData(generateDispatch.testConnection(dataSource));
        result.setTime(System.currentTimeMillis() - now);
        return result;
    }
}
